package com.kusej.idno.generation;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.ui.Messages;
import com.kusej.idno.generation.utils.IDCardUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Data
public class CreateIdCard {
    private JPanel contentPanel;
    private JRadioButton maleRadio;
    private JTextField birthday;
    private JComboBox<RegionModel> provinceComboBox;
    private JButton generateButton;
    private JTextArea result;
    private JRadioButton femaleRadio;
    private JComboBox<RegionModel> cityComboBox;
    private JComboBox<RegionModel> districtComboBox;
    private JTextField num;
    private JLabel warning;
    private JButton setting;
    private ButtonGroup sexButtonGroup;

    public CreateIdCard() {
        provinceComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                RegionModel selectedItem = (RegionModel) provinceComboBox.getSelectedItem();
                if (selectedItem != null && !selectedItem.getName().equals(Global.defaultProvince.getName())) {
                    // 初始化市级
                    List<RegionModel> regionModels = Global.regionCity.get(selectedItem.getId());
                    cityComboBox.removeAllItems();
                    cityComboBox.addItem(Global.defaultCity);
                    for (RegionModel city : regionModels) {
                        cityComboBox.addItem(city);
                    }
                    districtComboBox.removeAllItems();
                    districtComboBox.addItem(Global.defaultDistrict);
                }
            }
        });
        cityComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                RegionModel selectedItem = (RegionModel) cityComboBox.getSelectedItem();
                if (selectedItem != null && !selectedItem.getName().equals(Global.defaultCity.getName())) {
                    // 初始化 区县级
                    List<RegionModel> regionModels = Global.regionDistrict.get(selectedItem.getId());
                    districtComboBox.removeAllItems();
                    districtComboBox.addItem(Global.defaultDistrict);
                    for (RegionModel city : regionModels) {
                        districtComboBox.addItem(city);
                    }
                }
            }
        });
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                try {
                    generateIdCard();
                } catch (Exception e) {
                    e.printStackTrace();
                    Messages.showErrorDialog(e.getMessage(), "ERROR");
                }
            }
        });
        setting.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                try {
                    DefaultData defaultData = new DefaultData();
                    defaultData.setNum(num.getText());
                    defaultData.setBirthday(birthday.getText());
                    defaultData.setCityName(((RegionModel) Objects.requireNonNull(cityComboBox.getSelectedItem())).getFullName());
                    defaultData.setDistrictName(((RegionModel) Objects.requireNonNull(districtComboBox.getSelectedItem())).getFullName());
                    defaultData.setProvinceName(((RegionModel) Objects.requireNonNull(provinceComboBox.getSelectedItem())).getFullName());
                    defaultData.setIsMale(maleRadio.isSelected());
                    if (StringUtils.isBlank(defaultData.getDistrictName())){
                        throw new RuntimeException("请选择省市区!");
                    }
                    DefaultData.save(defaultData);
                    Messages.showMessageDialog("Success：重置成功", "Message", AllIcons.Actions.Commit);
                } catch (Exception e) {
                    e.printStackTrace();
                    Messages.showErrorDialog(e.getMessage(), "ERROR");
                }
            }
        });
    }


    public JComponent createUIComponents() {
        setDefaultValue();
        generateIdCard();
        return contentPanel;
    }

    private void setDefaultValue() {
        DefaultData defaultData = DefaultData.getInstance();
        this.birthday.setText(defaultData.getBirthday());
        // 默认山东省
        Collection<RegionModel> regionModels = Global.regionProvince.values();
        RegionModel provinceModel = Global.fullName2Model.get(defaultData.getProvinceName());
        provinceComboBox.removeAllItems();
        provinceComboBox.addItem(provinceModel);
        regionModels.remove(provinceModel);
        for (RegionModel city : regionModels) {
            provinceComboBox.addItem(city);
        }
        // 默认菏泽市
        regionModels = Global.regionCity.get(provinceModel.getId());
        RegionModel cityModel = Global.fullName2Model.get(defaultData.getCityName());
        cityComboBox.removeAllItems();
        cityComboBox.addItem(cityModel);
        regionModels.remove(cityModel);
        for (RegionModel city : regionModels) {
            cityComboBox.addItem(city);
        }
        // 默认定陶区
        regionModels = Global.regionDistrict.get(cityModel.getId());
        RegionModel districtModel = Global.fullName2Model.get(defaultData.getDistrictName());
        districtComboBox.removeAllItems();
        districtComboBox.addItem(districtModel);
        regionModels.remove(districtModel);
        for (RegionModel city : regionModels) {
            districtComboBox.addItem(city);
        }
        femaleRadio.setSelected(!defaultData.getIsMale());
    }


    private void generateIdCard() {
        String region = null;
        if (districtComboBox.getSelectedItem() != null && !districtComboBox.getSelectedItem().toString().equals(Global.defaultDistrict.toString())) {
            region = ((RegionModel) districtComboBox.getSelectedItem()).getCode();
        } else if (cityComboBox.getSelectedItem() != null && !cityComboBox.getSelectedItem().toString().equals(Global.defaultCity.toString())) {
            // 区县为空，则取城市
            region = ((RegionModel) cityComboBox.getSelectedItem()).getCode();
        } else if (provinceComboBox.getSelectedItem() != null && !provinceComboBox.getSelectedItem().toString().equals(Global.defaultProvince.toString())) {
            // 区县为空，则取省份
            region = ((RegionModel) provinceComboBox.getSelectedItem()).getCode();
        }
        if (StringUtils.isBlank(region)) {
            throw new RuntimeException("地址中省份不能为空");
        }
        int birth = NumberUtils.toInt(birthday.getText());
        if (birthday.getText().length() != 8 || birth == 0) {
            throw new RuntimeException("出生日期非法");
        }
        result.setText("");
        int n = NumberUtils.toInt(num.getText()) > 0 ? NumberUtils.toInt(num.getText()) : 5;
        for (int i = 0; i < n; i++) {
            String s = IDCardUtils.generateIDCardNumber(region, birthday.getText(), maleRadio.isSelected());
            result.append(s);
            result.append("\n");
        }
    }
}
